package com.gitee.wsl.compose.modifier.state

import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.autofill.AutofillNode
import androidx.compose.ui.autofill.AutofillType
import androidx.compose.ui.composed
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.layout.boundsInWindow
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalAutofill
import androidx.compose.ui.platform.LocalAutofillTree
import com.gitee.wsl.compose.modifier.ModifierStateScope

@OptIn(ExperimentalComposeUiApi::class)
internal fun Modifier.autofill(
    autofillTypes: List<AutofillType>,
    onFill: ((String) -> Unit),
) = composed {
    val autofill = LocalAutofill.current
    val autofillNode = remember { AutofillNode(onFill = onFill, autofillTypes = autofillTypes) }
    val autofillTree = LocalAutofillTree.current

    DisposableEffect(autofillNode.id) {
        autofillTree += autofillNode

        onDispose {
            autofillTree.children.remove(autofillNode.id)
        }
    }

    this
        .onGloballyPositioned {
            autofillNode.boundingBox = it.boundsInWindow()
        }
        .onFocusChanged { focusState ->
            autofill?.run {
                if (focusState.isFocused) {
                    requestAutofillForNode(autofillNode)
                } else {
                    cancelAutofillForNode(autofillNode)
                }
            }
        }
}

@OptIn(ExperimentalComposeUiApi::class)
fun ModifierStateScope.autofill(autofillTypes: List<AutofillType>,
                                onFill: ((String) -> Unit)){
    modifier = modifier.autofill(autofillTypes, onFill)
}